<template>
  <el-upload
      ref="upload"
      :action="url"
      :before-upload="prefixHandler"
      :headers="{Authorization: token}"
      :on-error="errorHandler"
      :on-progress="()=>this.isBtnAble=false"
      :on-success="checkResponse"
      accept="image/*"
      class="upload-box"
      drag
      list-type="picture"
      multiple>
    <i class="el-icon-upload"></i>
    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
    <div slot="tip" class="el-upload__tip">
      <el-tooltip :content="tip" :effect="tipTheme" placement="bottom">
        <el-checkbox v-model="isSecret" :disabled="!isLogin" style="margin-left: 5%">私密上传</el-checkbox>
      </el-tooltip>
      <el-button :disabled="!isBtnAble" circle icon="el-icon-delete" size="medium"
                 style="margin-left: 50%"
                 type="info" @click="clearAll"/>
      <el-alert v-if="isError" :closable="false" :description="errorMsg" effect="dark"
                show-icon style="margin-top: 3%" title="上传失败" type="error"/>
    </div>
  </el-upload>
</template>

<script>
import {mapState, mapGetters} from "vuex";

export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: "Upload",
  data() {
    return {
      isError: false,
      errorMsg: '',
      isBtnAble: true,
      isSecret: false,
    }
  },
  computed: {
    ...mapState(['username', 'serverUrl', 'token']),
    ...mapGetters(['isLogin', 'tipTheme']),
    tip() {
      return this.isLogin ? '上传图片仅能被自己看见' : '请先登录'
    },
    url() {
      return this.serverUrl + (this.isLogin && this.isSecret ? '/user' : '/api') + '/upload'
    },
    headers() {
      return {
        Authorization: this.token
      }
    }
  },
  methods: {
    errorHandler(err) {
      this.isError = true;
      this.errorMsg = `${err.method} ${err.status}: ${err.url}`;
      this.isBtnAble=true;
    },
    prefixHandler(file) {
      if (!/^image/.test(file.type)) {
        this.isError = true;
        this.errorMsg = '请选择图片文件上传！';
        return false
      } else return true
    },
    clearAll() {
      this.$refs.upload.clearFiles();
      this.isError = false;
    },
    checkResponse(res) {
      this.isBtnAble=true;
      if (res.status !== 0) {
        this.isError = true;
        this.errorMsg = res.msg;
      }
    }
  },
}
</script>

<style scoped>
  .upload-box {
    /*position: absolute;*/
    /*top: 50%;*/
    /*left: 2%;*/
    /*min-width: 360px;*/
    /*min-height: 300px;*/
    /*max-width: 22%;*/
    /*max-height: 100%;*/
    /*overflow: auto;*/
    position: relative;
    left: 22%;
    max-width: 60%;
  }
</style>